<!--
 * @Description:
 * @Author:
 * @Date: 2024-10-27 23:34:50
 * @LastEditTime: 2024-10-27 23:40:30
 * @LastEditors: XXX
-->
<template>
  <el-breadcrumb class="app-breadcrumb" separator-class="el-icon-arrow-right">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="item.path">
        <span v-if="item.redirect === 'noredirect' || index === breadcrumbs.length - 1" class="no-redirect">
          {{ t('route.' + item.meta.title) }} / {{ item.meta.title }}
        </span>
        <a v-else @click.prevent="handleLink(item)">{{ t('route.' + item.meta.title) }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script setup lang="ts">
import { onBeforeMount, reactive, watch } from 'vue';
import { useRoute } from 'vue-router'
import type { RouteLocationMatched } from 'vue-router'
import { useI18n } from 'vue-i18n'
import router from '@/router';
import { compile } from 'path-to-regexp'

const { t } = useI18n()
const currentRoute = useRoute()
let breadcrumbs = reactive<Array<RouteLocationMatched>>([])

const pathCompile = (path: string) => {
  const { params } = currentRoute
  const toPath = compile(path)
  return toPath(params)
}

const isDashboard = (route: RouteLocationMatched) => {
  const name = route?.name
  if (!name) {
    return false
  }
  return name.toString().trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
}

const getBreadCrumb = () => {
  let matched = currentRoute.matched.filter(item => item.meta?.title)
  const first = matched[0]
  if (isDashboard(first)) {
    matched = [{ path: '/dashboard', meta: { title: 'dashboard' } } as any].concat(matched)
  }
  breadcrumbs.length = 0
  breadcrumbs.push(...matched.filter(item => item.meta?.title && item.meta?.breadcrumb!== false));
}

const handleLink = (item: any) => {
  const { redirect, path } = item
  if (redirect) {
    router.push(redirect).catch((err: unknown) => {
      console.warn(err)
    })
  } else {
    router.push(pathCompile(path)).catch((err: unknown) => {
      console.warn(err)
    })
  }
}

watch(() => currentRoute.path, path => {
  if (path.startsWith('/redirect/')) {
    return
  }

  getBreadCrumb()
})

onBeforeMount(() => {
  getBreadCrumb()
})
</script>

<style lang="scss" scoped>
.el-breadcrumb__inner,
.el-breadcrumb__inner a {
  font-weight: 400 !important;
}

.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
